package com.lc.boxuegu.M_flatten;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaiyj
 * @date 2025/6/19 21:02
 */
public class Solution {

    public void flatten(TreeNode root) {
        dfs(root);
    }

    private TreeNode dfs(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode leftTail = dfs(root.left);
        TreeNode rightTail = dfs(root.right);
        if (leftTail != null) {
            leftTail.right = root.right; // 左子树链表 -> 右子树链表
            root.right = root.left; // 当前节点 -> 左右子树合并后的链表
            root.left = null;
        }
        return rightTail != null ? rightTail : leftTail != null ? leftTail : root;
    }


//
//
//    public TreeNode head;
//
//    public void flatten(TreeNode root) {
//        if(root == null){
//            return;
//        }
//        flatten(root.right);
//        flatten(root.left);
//        root.left = null;
//        root.right = head;
//        head = root;
//    }



    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
